﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint.WebControls;
using System.IO;
using System.Web.UI;
using System.Text.RegularExpressions;
using Microsoft.SharePoint;
using System.Diagnostics;

namespace LanguageConfigurationSolution
{
    /// <summary>
    /// This Control will render a localized text from a lookup-field. The destination list of the lookup should have columns for each supported localized language.
    /// </summary>
    public class LookupLanguageFieldDisplay : Control
    {
        public string ConfigurationListName { get; set; }

        public string FieldName { get; set; }

        protected override void Render(System.Web.UI.HtmlTextWriter output)
        {
            output.Write(GetText());
        }

        protected string GetText()
        {
            string result = string.Empty;

            if (!string.IsNullOrEmpty(FieldName))
            {
                try
                {
                    // Load the default field value from the specified FieldName of the current Page
                    if (SPContext.Current != null && SPContext.Current.ListItem != null)
                    {
                        SPField field = SPContext.Current.ListItem.Fields.GetFieldByInternalName(FieldName);

                        if (field is SPFieldLookup)
                        {
                            string fieldValue = SPContext.Current.ListItem[field.Id].ToString();
                            SPFieldLookupValue lookupField = new SPFieldLookupValue(fieldValue);
                            result = ConfigurationReader.GetConfigurationValue(lookupField.LookupValue, ConfigurationListName , "" );
                        }
                    }
                }
                catch (Exception ex)
                {
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        EventLog.WriteEntry(this.GetType().FullName, string.Format("Failed on FieldName \"{0}\"\r\n{1}" ,FieldName, ex.ToString()));
                    });
                }
            }
            

            return result;
        }
    }
}
